package org.intrasearch.core;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Set;
import java.util.TreeSet;

import static com.google.common.collect.ImmutableSortedSet.copyOf;

public class DirectoryArtifactImpl extends ResourceArtifactBase<DirectoryArtifact> implements DirectoryArtifact
{
    private Set<ArtifactId> containsFiles;
    private ArtifactId parent;

    public DirectoryArtifactImpl(String name, Set<String> urls, Set<ArtifactId> containsFiles, ArtifactId parent)
    {
        super(urls, name);
        this.containsFiles = copyOf(containsFiles);
        this.parent = parent;
    }

    public Set<ArtifactId> getFiles()
    {
        return containsFiles;
    }

    public ArtifactId getParent()
    {
        return parent;
    }

    public DirectoryArtifact merge(DirectoryArtifact nextArtifact)
    {
        TreeSet<ArtifactId> treeSet = new TreeSet<ArtifactId>(containsFiles);
        treeSet.addAll(nextArtifact.getFiles());
        return new DirectoryArtifactImpl(name, mergeUrls(nextArtifact), copyOf(treeSet), parent);
    }

    @Override
    protected ArtifactId generateArtifactId()
    {
        return ArtifactId.compose(parent, name);
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException
    {
        super.writeExternal(out);
        out.writeObject(parent);
        out.writeObject(containsFiles);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        super.readExternal(in);
        parent = (ArtifactId) in.readObject();
        containsFiles = (Set<ArtifactId>) in.readObject();
    }
}
